name: Build and Test Python Wheel

on:
  push:
    # Ensures the workflow is triggered by version tags.
    tags:
      - 'v*'

jobs:
  build-wheel:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Extract Version Tag
        id: get_version
        run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_ENV

      - name: Build Wheel
        run: |
          pip install build
          python -m build --wheel
          echo "WHEEL_FILE=$(ls dist/*.whl)" >> $GITHUB_ENV

      - name: Upload Artifact
        uses: actions/upload-artifact@v4
        with:
          name: nemoguardrails-${{ env.VERSION }}.whl
          path: dist/nemoguardrails-${{ env.VERSION }}-py3-none-any.whl

  test-wheel:
    needs: build-wheel
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: [ '3.8', '3.9', '3.10', '3.11' ]
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: ${{ matrix.python-version }}

      - name: Extract Version Tag
        run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_ENV

      - name: Download Artifact
        uses: actions/download-artifact@v4
        with:
          name: nemoguardrails-${{ env.VERSION }}.whl

      - name: Install Wheel
        run: |
          pip install nemoguardrails-${{ env.VERSION }}-py3-none-any.whl
          pip install nemoguardrails-${{ env.VERSION }}-py3-none-any.whl[dev]

      - name: Test with pytest
        run: |
          pytest

      # Next, we also do a basic test of the server.

      - name: Start server in the background
        run: |
          nemoguardrails server &
          echo "SERVER_PID=$!" >> $GITHUB_ENV

      - name: Wait for server to be up
        run: |
          echo "Waiting for server to start..."
          while ! curl --output /dev/null --silent --head --fail http://localhost:8000; do
            printf '.'
            sleep 1
          done
          echo "Server is up!"

      - name: Check server status
        run: |
          RESPONSE_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8000/v1/rails/configs)
          if [ "$RESPONSE_CODE" -ne 200 ]; then
            echo "Server responded with code $RESPONSE_CODE."
            exit 1
          fi

      - name: Stop server
        if: ${{ success() }}
        run: |
          kill $SERVER_PID
